import json
import re

from django import http
from django.contrib.auth import login, authenticate, logout
from django.views import View
from django_redis import get_redis_connection

from apps.cart.utils import merge_cart_cookie_to_redis
from apps.users.models import User, Address
from django.http import JsonResponse

from apps.users.utils import generate_verify_token, check_verify_token
from celery_tasks.email.tasks import send_verify_mail
from utils.viewmixin import LoginMixin


class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        """
        :param request: 请求对象
        :param username: 用户名
        :return: JSON
        """
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    def post(self, request):
        # 步骤
        # 1. 接受请求
        body_byte = request.body
        # 获取json格式数据 转为字典
        body_dict = json.loads(body_byte)

        # 2. 获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")

        # 3. 验证数据
        # 3.1 验证数据是否为空 有没有传数据
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"code": "400", "errmsg": "register fail"})
        # 3.2 正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": "400", "errmsg": "register fail"})

        # 短信验证码验证
        # 从redis里获取短信验证码
        redis_cli = get_redis_connection("code")
        redis_sms_code = redis_cli.get("sms_%s" % mobile)

        # 判断是否过期
        if redis_sms_code is None:
            return JsonResponse({"code": 400, "errmsg": "短信验证码过期"})
        # 和用户发过来验证码的对比
        if redis_sms_code.decode().lower() != sms_code.lower():
            return JsonResponse({"code": 400, "errmsg": "短信验证按吗输入错误"})

        # 4. 生成用户保存到数据库
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "用户保存失败"})
        print("保存用户到数据库成功")

        # 状态保持
        login(request, user)

        response = JsonResponse({"code": '0', "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 5. 返回响应（json数据）
        return response


"""
前端：  用户 用户名 密码 勾选是否记住用户 点击登录按钮 发送axios请求

后端： 
        接收请求： JSON数据  验证数据
        
        路由： post 'login/'
        
        业绩逻辑：验证数据 验证用户名和密码是否正确 状态保持
        响应 JSON格式
        {"code": 0, "errmsg": "OK"}
        {"code": 400, "errmsg": "login fail"}
"""


class LoginView(View):
    def post(self, request):
        # 1 接受数据 json
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get("username")
        password = data_dict.get("password")
        remembered = data_dict.get("remembered")
        # 2 验证数据 是否为空
        if not all([username, password, remembered]):
            return JsonResponse({"code": "400", "errmsg": "参数不全"})

        # 根据用户传入的username的值 判断是手机号还是用户名
        # 然后设置用户验证是使用手机号还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 3.验证用户名和密码是否正确
        # 如果用户名密码正确 返回User对象 否则返回None
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({"code": "400", "errmsg": "用户名密码错误"})
        # 4.状态保持
        login(request, user)
        # 5.判断是否记住登录状态 设置session的有效期
        if remembered:
            # 记住登录 默认None 有效期为 2周
            request.session.set_expiry(None)
        else:
            # 不记住登录
            request.session.set_expiry(0)

        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 登录合并添加购物车
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        # 6 返回响应
        return response


"""
前端：  用户 在首页点击退出 发送axios请求

后端： 

        路由： post 'logout/'

        业绩逻辑：清空session和cookie
        响应 JSON格式
        {"code": 0, "errmsg": "OK"}
        {"code": 400, "errmsg": "logout fail"}
"""


class LogoutView(View):
    def delete(self, request):
        # 1.调用logout清空状态保持的session
        logout(request)
        # 2.删除cookie里的username
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        response.delete_cookie('username')

        return response


# LoginRequiredMixin验证用户是否登录
class UserInfoView(LoginMixin, View):

    def get(self, request):
        info_data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }

        return JsonResponse({
            'code': 0,
            'errmsg': '个人中心',
            "info_data": info_data
        })


"""
前端 点击设置 输入邮箱地址 点击保存 发送请求

后端  接收请求 邮箱的地址
      逻辑 保存邮箱地址到用户信息里，发送一封激活邮件
      响应 json数据
      路由 /emails/
      请求方式 put
"""


class SaveEmailView(View):
    def put(self, request):
        # 1.获取数据 邮箱地址
        json_body = request.body
        data_dict = json.loads(json_body)
        email = data_dict.get("email")

        if not email:
            return JsonResponse({"code": "400", "errmsg": "邮箱地址不能为空"})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({"code": "400", "errmsg": "邮箱格式错误"})
        # 2.保存邮箱地址
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "邮箱保存失败"})

        # 3.发送邮件
        print("保存成功")
        subject = "美多商城"  # 标题
        recipient_list = [email]  # 接收方地址

        token = generate_verify_token(request.user.id)
        # 可以get拿到token
        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        send_verify_mail.delay(subject=subject, html_message=html_message, recipient_list=recipient_list)

        # 4.返回响应
        return JsonResponse({"code": "0", "errmsg": "ok"})


"""
前端发送
    用户点击邮箱里的激活链接 发送 /emails/verification/?token=xxx请求
    
后端： 接受请求 获取参数 验证
      逻辑 解密token得到user_id根据user_id去数据库查询数据 修改邮箱激活字段
      返回相应
      
      路由 put /emails/verification/?token=xxx
"""


class EmailVerifyView(View):
    def put(self, request):
        # 1.获取参数
        token = request.GET.get("token")

        # 2.校验参数
        if token is None:
            return JsonResponse({"code": "400", "errmsg": "缺少token"})
        # 3.解密获取user_id
        user_id = check_verify_token(token)

        # 4.判断user_id是否为空
        if user_id is None:
            return JsonResponse({"code": "400", "errmsg": "token错误"})

        # 5.查询用户 数据
        try:
            user = User.objects.get(id=user_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "查不到用户"})

        # 6.修改用户邮箱激活字段为True
        user.email_active = True
        user.save()
        # 7.返回相应
        return JsonResponse({"code": "0", "errmsg": "ok"})


"""
需求 增加一个收货地址

前端 用户填写完收货地址 点击保存 发送一个axios请求 把数据传过来

后端 请求 接收请求 获取和验证参数
     逻辑 把数据保存到仓库
     返回响应
路由 POST  addresses/create/

 {'code':0,"errmsg":"ok","address":{"title":"老家地址","mobile":"1551234431",,,,}}

"""


class AddressCreateView(LoginMixin, View):
    """用户地址信息增加"""

    def post(self, request):
        # 1接收请求
        body = request.body
        data_dict = json.loads(body)

        # 2获取参数
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        # 3验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({"code": "400", "errmsg": "参数不全"})
        # 正则验证
        # if not all([receiver, province_id, city_id, district_id, place, mobile]):
        #     return http.HttpResponseBadRequest('缺少必传参数')
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.HttpResponseBadRequest('参数mobile有误')
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return http.HttpResponseBadRequest('参数tel有误')
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return http.HttpResponseBadRequest('参数email有误')

        # 4保存数据到数据库
        # 创建一个Address对象address
        # address = Address(xxx=xxx)
        # address.save()

        user = request.user
        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "保存数据失败"})

        # 数据转为字典
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 5返回响应
        return JsonResponse({'code': 0, "errmsg": "ok", "address": address_dict})


"""
- 路由  addresses/
- 步骤
  - 1获取用户对象
  - 2查询当前用户 的所有地址信息
  - 3转为字典数据
  - 4 返回
"""


class AddressView(LoginView, View):
    """用户地址信息显示查看"""

    def get(self, request):
        # 1.获取用户对象
        user = request.user
        # 2查询当前用户 的所有地址信息
        # user.addresses 这样方式会拿到所有数据 包括逻辑删除的
        addresses = Address.objects.filter(user=user, is_deleted=False)  # is_deleted=False过滤查询没有删除的

        # 3.转为字典数据
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 4.返回
        return JsonResponse({'code': 0, "errmsg": "ok", "addresses": addresses_list})


class UpdateDestroyAddressView(LoginMixin, View):
    """修改地址"""

    def put(self, request, address_id):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, "errmsg": "缺少必传参数"})

        # 正则验证
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        #
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 判断地址是否存在，并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, "errmsg": "更新地址失败"})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址信息"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)
            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, "errmsg": "删除地址失败"})
        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginMixin, View):
    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(LoginMixin, View):
    """设置地址标题"""

    def put(self, request, address_id):
        # 1.接收参数 地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get("title")
        try:
            # 2.查询地址
            address = Address.objects.get(id=address_id)

            # 3.设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置地址标题成功'})


class ChangePasswordView(LoginMixin, View):
    """修改密码"""

    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        dict = json.loads(request.body.decode())
        old_password = dict.get("old_password")
        new_password = dict.get("new_password")
        new_password2 = dict.get("new_password2")

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)

        # 删除cookie
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response
